/**
 * @file ChatSession.cs
 * @author Zane Mayo
 * @date 7/5/2009
 */

using System;
using System.Collections.Generic;

namespace MxitAPI {
	
	/**
	 * Holds the details of an active chat
	 */
	public class ChatSession {

        public event ChatSessionNewMessageEventHandler NewMessagesReceived;

		private static log4net.ILog log = log4net.LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType );
		
		private readonly int chatSessionId;  /// A unique identifier for this chat session
		private readonly int contactId;  /// The unique contactId for the contact associated with this chat session
		public List<MxitMessage> Messages { get; set; }  /// A list of messages for this chat sessions
		//public bool newMessagesExist { get; set; } /// A flag to show whether messages exist that have not been displayed by the Gui
		private int? newMessageStartIndex;  /// The ( nullable ) index that shows where the first uncollected message is in the list
		
		public ChatSession( int chatSessionId, int contactId ) {
			this.chatSessionId = chatSessionId;
			this.contactId = contactId;
			newMessageStartIndex = null;
			Messages =  new List<MxitMessage>();
		}
		
		public int ChatSessionId {
			get { return chatSessionId; }
		}
		
		public int ContactId {
			get { return contactId; }
		}
		
		public bool NewMessagesExist() {
			return ( newMessageStartIndex != null );
		}
		
		/**
		 * Adds a message to the message list updates according to the fact that it is unread
		 * @message the message that is to be added to this ChatSession
		 */
		public void AddMessage( MxitMessage message ) {
			if ( message == null ) {
				log.Error( "Message to be added was null" );
				return;
			}
			Messages.Add( message );
			
			log.InfoFormat( "New message recieved. text [{0}]", message.MessageText );
			
			if ( newMessageStartIndex == null )
				newMessageStartIndex = Messages.Count - 1;
		}
		
		/**
		 * Get the oldest unread message. 
		 * @return the oldest unread message, null if there are no unread messages
		 */
		public MxitMessage GetNextNewMessage() {
			if ( !NewMessagesExist() )
				return null;
			
			int indexToReturn = newMessageStartIndex.Value;
			
			if ( newMessageStartIndex == Messages.Count - 1 ) 
				newMessageStartIndex = null;
			else
				++newMessageStartIndex;
				
			return Messages[ indexToReturn ];
		}

        public void DoNewMessageRecieved() {
            NewMessagesReceived( this, null );
        }
		
		
	}
}
